package cn.hacynn.nd.common.utils;

import cn.hacynn.nd.common.properties.MailProperties;
import jakarta.mail.MessagingException;
import jakarta.mail.Session;
import jakarta.mail.internet.MimeMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;

/**
 * 邮箱工具类
 */
@Component
public class JavaMailUtil {

    @Autowired
    private JavaMailSender mailSender;

    @Autowired
    private MailProperties mailProperties;

    /**
     * 群发
     */
//    public void sendMail(String subject, String text, List<User> users) throws MessagingException {
//        String[] userEmail = new String[users.size()];
//        for (int i = 0; i < users.size(); i++) {
//            User user = users.get(i);
//            userEmail[i] = user.getEmail();
//        }
//        sendMailPublic(subject, text, userEmail);
//
//    }

    /**
     * 发给一个人
     */
    public void sendMailForOnePeople(String userEmail, String subject, String text) throws MessagingException {
        sendMailPublic(subject, text, userEmail);
    }
    
    private <T> void sendMailPublic(String subject, String text, T userEmail) throws MessagingException {
        //一个复杂的邮箱
        MimeMessage mimeMessage = mailSender.createMimeMessage();

        Session session = mimeMessage.getSession();
        //  解决本地DNS未配置 ip->域名场景下，邮件发送太慢的问题
        session.getProperties().setProperty("mail.smtp.localhost", "192.168.xxx");

        //组装
        MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage);
        //即为邮件发送者，一般设置在配置文件中
        mimeMessageHelper.setFrom(mailProperties.getEmail());
        if (userEmail instanceof String[]) {
            String[] userEmailArray = (String[]) userEmail;
            mimeMessageHelper.setTo(userEmailArray);
        }
        if (userEmail instanceof String) {
            String userEmailString = (String) userEmail;
            mimeMessageHelper.setTo((userEmailString));
        }
        //邮件主题
        mimeMessageHelper.setSubject(subject);
        //邮件内容
        mimeMessageHelper.setText(text, true);
        mailSender.send(mimeMessage);
    }

}
